package com.sheeran.aichat.service.bigmodel.impl;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.sheeran.aichat.config.setting.BigModelConfig;
import com.sheeran.aichat.dto.bigmodel.BigModelResponseDTO;
import com.sheeran.aichat.dto.bigmodel.BigModelToolsResponseDTO;
import com.sheeran.aichat.dto.bigmodel.ChatCompletionRequestDTO;
import com.sheeran.aichat.dto.bigmodel.ChatToolsRequestDTO;
import com.sheeran.aichat.feign.bigmodel.BigModelClient;
import com.sheeran.aichat.service.bigmodel.IOpenAI;
import com.sheeran.aichat.utils.bigmodel.BearerTokenUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author: sheeran
 * @create: 2025/02/11
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ChatGLM implements IOpenAI {

//    @NacosValue(value = "${bigmodel.api-key}", autoRefreshed = true)
//    private String apiKey;

    private final BigModelClient bigModelClient;
    private final BigModelConfig bigModelConfig;

    private String getBearerToken() {
        String apiKey = bigModelConfig.getApiKey();
        if (apiKey == null || apiKey.trim().isEmpty()) {
            log.error("API key is not configured properly.");
            throw new IllegalStateException("API key is not configured properly.");
        }
        return "Bearer " + BearerTokenUtils.getToken(apiKey);
    }

    @Override
    public BigModelResponseDTO completions(ChatCompletionRequestDTO requestDTO) {
        try {
            String token = getBearerToken();
            BigModelResponseDTO completions = bigModelClient.completions(token, requestDTO);
            log.debug("completions response:{}", completions);
            return completions;
        } catch (Exception e) {
            log.error("Error in completions method", e);
            throw new RuntimeException("Error in completions method", e);
        }
    }

    @Override
    public BigModelToolsResponseDTO tools(ChatToolsRequestDTO requestDTO) {
        try {
            String token = getBearerToken();
            BigModelToolsResponseDTO tools = bigModelClient.tools(token, requestDTO);
            log.debug("tools response:{}", tools);
            return tools;
        } catch (Exception e) {
            log.error("Error in tools method", e);
            throw new RuntimeException("Error in tools method", e);
        }
    }
}
